package org.an.proj.contacts.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import butterknife.Bind;
import butterknife.ButterKnife;
import com.nineoldandroids.view.ViewHelper;
import link.config.AgentConfig;
import link.service.LoginManagerService;
import org.an.ku.base.BaseTabsActivity;
import org.an.ku.util.ACache;
import org.an.ku.util.Tool;
import org.an.proj.contacts.MyApplication;
import org.an.proj.contacts.R;
import org.an.proj.contacts.config.ACacheKey;
import org.an.proj.contacts.config.LogUtil;
import org.an.proj.contacts.eventbus.EventController;
import org.an.proj.contacts.eventbus.EventTag;
import org.an.proj.contacts.model.bean.ConfigInfoVo;
import org.an.proj.contacts.model.response.Result;
import org.an.proj.contacts.ui.contact.ContactFragment;
import org.an.proj.contacts.ui.mine.MineFragment;
import org.an.proj.contacts.ui.msg.MsgFragment;
import org.an.proj.contacts.ui.side.SlidingFragment;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 创建时间：2016年10月13日14:48 <br>
 * 作者：fuchaoyang <br>
 * 描述：主页，这里有个bug，切换横竖屏后会导致动画失效
 */
public class MainActivity extends BaseTabsActivity {

  @Bind(R.id.drawer_layout) DrawerLayout mDrawerLayout;
  @Bind(R.id.drawer_container) FrameLayout mDrawerContainer;

  /**
   * 点击那个前台通知就会走onNewIntent
   */
  @Override protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    LogUtil.e("MainActivity", "onNewIntent:" + intent.getAction());
  }

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ButterKnife.bind(this);
    EventController.register(this);
    initSlidingFragment();
    if (AgentConfig.getInstance().getAgentInfo() != null) {
      startService(new Intent(this, LoginManagerService.class));
    }
  }

  /**
   * EventBus 3.0接收Event，这里已onEvent开头只是为了命名统一，不强制命名;
   * 规范：post Event必须写到EventController中，且接收的地方必须要链接到对应（使用@see或{@link}）
   *
   * @param tag tag
   * {@link EventController#postToggleSlidingEvent(boolean)}
   */
  @Subscribe(threadMode = ThreadMode.MAIN) public void onEventToggleSliding(
      EventTag.TagToggleSliding tag) {
    //    mDrawerLayout.openDrawer(Gravity.LEFT, true);
    // 也可以 判断mDrawerLayout.isDrawerOpen(Gravity.LEFT)是否开启
    if (tag.isOpen) {
      mDrawerLayout.openDrawer(Gravity.LEFT);
    } else {
      mDrawerLayout.closeDrawer(Gravity.LEFT);
    }
  }

  @Override protected void onDestroy() {
    EventController.unregister(this);
    super.onDestroy();
  }

  @Override protected boolean openSwipeBack() {
    return false;
  }

  @Override protected boolean isFull() {
    return true;
  }

  private void initSlidingFragment() {
    mDrawerContainer.getLayoutParams().width = Tool.getScreenWidth(this) / 2;
    // 第二个参数表明作用的位置
    // LOCK_MODE_LOCKED_CLOSED 表示不允许手势操作，只允许通过代码操作，起初关闭
    // LOCK_MODE_LOCKED_OPEN 表示不允许手势操作，只允许通过代码操作，起初展开
    // LOCK_MODE_UNLOCKED 默认这种默认。表示都可以，默认关闭
    mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.LEFT);
    mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
    // api >= 21
    //mDrawerLayout.setDrawerElevation(320);
    //mDrawerLayout.setScrimColor(getResources().getColor(R.color.color_00beb3));
    //mDrawerLayout.setDrawerListener();
    mDrawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
      @Override public void onDrawerSlide(View drawerView, float slideOffset) {
        View mContent = mDrawerLayout.getChildAt(0);
        View mMenu = drawerView;
        float scale = 1 - slideOffset; // 1-0
        float rightScale = 0.8f + scale * 0.2f;

        // 也可以用id
        if (drawerView.getTag().equals(getString(R.string.tag_sliding_left))) {
          float leftScale = 1 - 0.3f * scale;
          ViewHelper.setScaleX(mMenu, leftScale);
          ViewHelper.setScaleY(mMenu, leftScale);
          ViewHelper.setAlpha(mMenu, 0.6f + 0.4f * (1 - scale));
          ViewHelper.setTranslationX(mContent, mMenu.getMeasuredWidth() * (1 - scale));
          ViewHelper.setPivotX(mContent, 0);
          ViewHelper.setPivotY(mContent, mContent.getMeasuredHeight() / 2);
          // 这里必须主动调一次invalidate,不然4.4手机会有问题
          mContent.invalidate();
          ViewHelper.setScaleX(mContent, rightScale);
          ViewHelper.setScaleY(mContent, rightScale);
        } else {
          ViewHelper.setTranslationX(mContent, -mMenu.getMeasuredWidth() * slideOffset);
          ViewHelper.setPivotX(mContent, mContent.getMeasuredWidth());
          ViewHelper.setPivotY(mContent, mContent.getMeasuredHeight() / 2);
          mContent.invalidate();
          ViewHelper.setScaleX(mContent, rightScale);
          ViewHelper.setScaleY(mContent, rightScale);
        }
      }
    });

    Fragment slidingFragment = getSupportFragmentManager().findFragmentById(R.id.drawer_container);
    if (slidingFragment == null) {
      // 上面可以使用findFragmentById,这里可以不加tag
      getSupportFragmentManager().beginTransaction()
          .add(R.id.drawer_container, new SlidingFragment(), "SlidingFragment")
          .commit();
    }
  }

  @Override protected int getLayoutResId() {
    return R.layout.activity_main;
  }

  @Override protected void initTabs() {
    setDividerDrawable(null);
    Result<ConfigInfoVo> result =
        (Result) ACache.get(MyApplication.getInstance()).getAsObject(ACacheKey.TAB);

    /*if (result != null) {
      ConfigInfoVo data = result.data;
      List<ConfigInfoVo.ConfigItemVo> tab = data.tab;
      for (ConfigInfoVo.ConfigItemVo configItemVo : tab) {
        Fragment fragment = ConfigManager.getTabFragment(configItemVo.actionUrl);
        String title = configItemVo.title;
        if (SchemaUtil.SCHEME.equals(SchemaUtil.getScheme(configItemVo.imgUrl))) {
          // 取本地图片
          addTab(fragment.getClass(), title, ConfigManager.getTabImg(configItemVo.imgUrl));
        } else {
          // 加载网络图片
          addTab(fragment.getClass(), title, configItemVo.imgUrl);
        }
      }
    }*/

    addTab(MsgFragment.class, getString(R.string.str_tab_msg), R.drawable.icon_msg_selector);
    addTab(ContactFragment.class, getString(R.string.str_tab_contact),
        R.drawable.icon_contact_selector);
    addTab(MineFragment.class, getString(R.string.str_tab_mine), R.drawable.icon_mine_selector);
    if (getTabCount() > 0) setCurrentTab(1);
  }

  @Override public void onBackPressed() {
    if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
      mDrawerLayout.closeDrawer(Gravity.LEFT);
    } else if (mDrawerLayout.isDrawerOpen(Gravity.RIGHT)) {
      mDrawerLayout.closeDrawer(Gravity.RIGHT);
    } else {
      super.onBackPressed();
    }
  }
}
